import React, { Component, createRef } from 'react'
import Captcha from "../../components/Captcha"
// ant导入
import { Form, Input, Button, message } from 'antd';
import { UserOutlined, LockOutlined,KeyOutlined } from '@ant-design/icons';
// 导入请求资源
import url from "../../config/url"
import req from "../../http/req"
import { withRouter } from 'react-router-dom';
// css资源导入
import "./MobileLogin.css"


class MobileLogin extends Component {
  constructor(props) {
    super(props);
    this.capRef = createRef();
    this.formRef = createRef();
  }
  t = null
  // 初始 state
  state={
    time:10,  //倒计时的时长
    sentCode: false, // 标志是否已完成短信的获取
    enabled: true,  
  }
  
  render() {
    return (
      <>
        <Form
          // 用ref获取表单的数据
          ref={this.formRef}
          name="normal_login"
          className="login-form"
          initialValues={{}}
          onFinish={this.onFinish}
        >
          {/* 手机号 */}
          <Form.Item
            name="mobile"
            rules={[{required: true, message: '请输入正确的手机号!'}]}
          >
            <Input prefix={<UserOutlined className="site-form-item-icon" />} maxLength="11" placeholder="手机号" />
          </Form.Item>
          {/* 验证码 */}
          <Form.Item
            name="captcha"
            rules={[
              {
                required: true,
                message: '请输入图形验证码 !',
              },
            ]}
          >
            <div className="captcha">
              <Input prefix={<KeyOutlined className="site-form-item-icon" />} type="text" placeholder="图形验证码" maxLength="6" />
              <Captcha setKey = {this.getKey} ref={this.capRef} />
            </div>
          </Form.Item>
          {/* 密码 */}
          <Form.Item
            name="code"
            rules={[
              {
                required: true,
                message: '请输入正确的短信验证码',
              },
            ]}
          >
            <div className="messageCaptcha">
              <Input
                prefix={<LockOutlined className="site-form-item-icon" />}
                type="text"
                placeholder="短信验证码"
              />
              <Button disabled={!this.state.enabled} onClick={this.sendCode}>
                {this.state.enabled ? "获取短信" : `重新获取(${this.state.time})`}
              </Button>
            </div>
          </Form.Item>
          {/* 登录按钮 */}
          <Form.Item>
            <Button
              type="primary" 
              htmlType="submit" 
              className="login-form-button"
              disabled = {!this.state.sentCode} 
            >
              登 录
            </Button>
          </Form.Item>
        </Form>
      </>
    )
  }
  // 提交处理程序
  onFinish = (values) => {
    // 判断是否有获取短信
    if(this.state.sentCode){
      // 有获取短信
      let {code,mobile} = values
          let params = {mobile,code,requestId: this.state.requestId}
          req.post(url.MobileLogin, params)
            .then((res)=>{
              if(res.data.errNo === 0){
                message.success("登录成功！",2,()=>{
                  this.props.history.push("/dashboard")
                })
              }else{
                message.error(res.data.errText, 2, ()=>{
                  // 刷新表单
                  this.capRef.current.loadCaptcha()
                });
              }
            })
    }else{
      // 没有获取短信
      message.error("请获取短信验证码",2)
    }
    
  };

  // 获取验证码key值的方法
  getKey = (key) => {
    this.setState({
      key,
    });
  };
  // 获取短信验证码
  sendCode = ()=>{
    let {mobile,captcha} = this.formRef.current.getFieldsValue()
    if(/^1[3-9]\d{9}$/.test(mobile) && captcha){
      // 数据没问题
      req.post(url.VerifyCaptcha,{captcha,key: this.state.key})
        .then((res)=>{
          if(res.data.errNo === 0){
            // 存储token值,后面发送短信需要
            let token = res.data.context.token
            req.post(url.SendCode,{mobile,token,type: 0})
              .then(ret => {
                if(ret.data.errNo === 0){
                  this.setState({
                    requestId: ret.data.requestId,
                    sentCode: true
                  })
                  message.success("成功")
                }else{
                  message.error(res.data.errText,2,()=>{this.capRef.current.loadCaptcha()})
                }
              })

          }else{
            message.error(res.data.errText,2,()=>{this.capRef.current.loadCaptcha()})
          }
        })
    }else{
      // 有问题
      message.error("请输入合法手机号和图形验证码")
    }
    // 3 倒计时
    this.timedown()
  }

  // 倒计时
  timedown = ()=>{
    if(this.state.time === 0){
      this.setState({
        time: 10, //时间重置
        enabled: true, // 按钮可以被点击
      })
    }else{
      this.setState({
        time: this.state.time - 1,
        enabled: false,
      })
      this.t = setTimeout(()=>{this.timedown()},1000)
    }
  }
  // 清理副作用
  componentWillUnmount(){
    clearTimeout(this.t)
  }

}

export default withRouter(MobileLogin);

